<template>
  <div>
    <Nav></Nav>
    <div class="container-fluid" style="margin-top: 100px">
      <!-- 看板 -->
      <div class="row">
        <div class="col-md-1"></div>
        <div class="col-md-10">
          <div class="row">
            <div class="col-md-5">
              <div class="card">
                <div class="card-header bg-light text-center">用户占比分析</div>
                <div class="card-body">
                  <div class="ibox float-e-margins">
                    <div class="ibox-title">
                      <h5>
                        <span
                          style="font-size: 16px"
                          class="label label-success"
                          >用户来源分布</span
                        >
                      </h5>
                    </div>
                    <div class="ibox-content">
                      <div
                        class="echarts"
                        id="userAddressPie"
                        style="height: 300px"
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-7">
              <div class="card">
                <div class="card-header bg-light text-center">用户占比分析</div>
                <div class="card-body">
                  <div class="ibox float-e-margins">
                    <div class="ibox-title">
                      <h5>
                        <span
                          style="font-size: 16px"
                          class="label label-success"
                          >用户访问量趋势</span
                        >
                      </h5>
                    </div>
                    <div class="ibox-content">
                      <div id="lineChart" style="height: 300px"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-md-1"></div>
      </div>
      <!-- 按钮组 -->
      <div class="row" style="margin-top: 20px">
        <div class="col-md-1"></div>
        <div class="col-md-10">
          <a
            href="#"
            @click="deleteBatchVipUser()"
            class="btn btn-sm btn-outline-danger"
            ><i class="fa fa-trash-o"></i> 批删除</a
          >
          <a href="/addUser" class="btn btn-outline-success btn-sm"
            ><i class="fa fa-user-plus"></i> 添加</a
          >
          <a href="#" class="btn btn-outline-success btn-sm"
          @click.prevent="exportUser()"
            ><i class="fa fa-file-excel-o"></i> 导出</a
          >
        </div>
        <div class="col-md-1"></div>
      </div>
      <div class="row">
        <div class="col-md-1"></div>
        <div class="col-md-10">
          <table class="table table-bordered table-hover">
            <thead>
              <tr class="bg-light">
                <th><input type="checkbox" name="id" id="id" /></th>
                <th>用户名</th>
                <th>年龄</th>
                <th>手机</th>
                <th>邮箱</th>
                <th>地址</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in vipUsers" :key="user.id">
                <td>
                  <input
                    type="checkbox"
                    name="selectedProducts"
                    class="item-checkbox"
                    :value="user.id"
                    v-model="selectedVipUserIds"
                  />
                </td>
                <td>{{ user.username }}</td>
                <td>{{ user.age }}</td>
                <td>{{ user.mobile }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.address }}</td>
                <td>
                  <a
                    class="btn btn-sm btn-outline-danger"
                    href="#"
                    @click.prevent="deleteVipUser(user.id)"
                    ><i class="fa fa-trash-o"></i>删除</a
                  >
                  <input
                    type="hidden"
                    id="userId_${userItem.index}"
                    th:value="${userItem.id}"
                  />
                  <a
                    class="btn btn-sm btn-outline-info"
                    href="#"
                    @click.prevent="editVipUser(user.id)"
                    ><i class="fa fa-edit"></i>编辑</a
                  >
                  <a
                    class="btn btn-sm btn-outline-success"
                    href="#"
                    @click.prevent="getVipUserInfo(user.id)"
                    ><i class="fa fa-info"></i>查看</a
                  >
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="col-md-1"></div>
      </div>
      <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6" style="text-align: center">
        <!-- 检查当前页码是否大于1 -->
        <a class="btn btn-outline-primary" v-if="currentPage > 1" @click="prevPage">上一页</a>
      <!-- 检查当前页码是否小于总页数 -->
      <a class="btn btn-outline-primary"  @click="nextPage">下一页</a>
        </div>
        <div class="col-md-3"></div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="UserList">
import Nav from "../Nav.vue";
import "../../assets/css/bootstrap.min.css";
import "../../assets/css/font-awesome.css";
import { ref, reactive, onMounted } from "vue";
import { getVipUserList, deleteUser ,exportVipUser,deleteBatchVip} from "../../api/vipuser";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { saveAs } from "file-saver";
import "../../assets/js/echarts.min.js";
const router = useRouter();
const vipUsers = reactive([]);
let selectedVipUserIds = ref([]);
const currentPage = ref(1); 
const totalPage = ref(0); 
const getVipUsers = async () => {
  const res = await getVipUserList(currentPage.value);
  if (res.data.code === 1) {
    totalPage.value = res.data.data.pages;
    vipUsers.splice(0, vipUsers.length, ...res.data.data.usersList);
  }
};
// / 上一页逻辑
const prevPage = async () => {
  if (currentPage.value > 1) {
  const res=  await getVipUserList(currentPage.value - 1);
   // 更新当前页码
   currentPage.value--;
   vipUsers.splice(
      0,
      vipUsers.length,
      ...res.data.data.usersList
    );
  }
};
// 下一页逻辑
const nextPage = async () => {
  if (currentPage.value < totalPage.value) {
   const res= await getVipUserList(currentPage.value +1);
   // 更新当前页码
   currentPage.value++;
   vipUsers.splice(
      0,
      vipUsers.length,
      ...res.data.data.usersList
    );
  }
};
const deleteBatchVipUser = async () => {
const res = await deleteBatchVip(selectedVipUserIds.value);
if (selectedVipUserIds.value.length === 0) {
    ElMessage.error("请选择要删除的会员");
    return;
  }
if (res.data.code === 1) {
  ElMessage.success("批量删除会员成功");
  await getVipUsers();
}
if (res.data.code === 0) {
  ElMessage.error("批量删除会员失败");
}
}
const deleteVipUser = async (id: number) => {
  const res = await deleteUser(id);
  if (res.data.code === 1) {
    ElMessage.success("删除成功");
    await getVipUsers();
  }
}
const getVipUserInfo = (id: number) => {
    router.push(`/userInfo/${id}`)
}
const editVipUser = (id: number) => {
    router.push(`/editUser/${id}`);
}
const exportUser = async () => {
  const res = await exportVipUser();
  if (res.status === 200) {
    ElMessage.success("会员信息导出成功");
    saveAs(res.data, "vipUser.xlsx");
  }
};
function getData1(){
    var pieChart = echarts.init(document.getElementById("userAddressPie"));
			fetch('/api/echart/userSources')
					.then(response => response.json())
					.then(data => {
						var pieoption = {
							title: {
								text: '',
								x: 'center'
							},
							tooltip: {
								trigger: 'item',
								formatter: "{a} <br/>{b} : {c} ({d}%)"
							},
							legend: {
								orient: 'vertical',
								x: 'left',
								data: data.legendData
							},
							calculable: true,
							series: [{
								name: '支付平台',
								type: 'pie',
								radius: '55%',
								center: ['50%', '60%'],
								data: data.data
							}]
						};
						pieChart.setOption(pieoption);
					})
}
function getData2(){
    var myChart = echarts.init(document.getElementById('lineChart'));

fetch('/api/echart/weeklyVisitData')
        .then(response => {
            if (!response.ok) {
                throw new Error('');
            }
            return response.json();
        })
        .then(data => {
            const dates = data.map(item => item.visitTime);
            const visits = data.map(item => item.visits);

            // 更新ECharts配置
         var   option = {
                title: {
                    text: '',
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['用户访问趋势']
                },
                toolbox: {
                    show: true,
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: dates
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} 次'
                    }
                },
                series: [
                    {
                        name: '用户访问趋势',
                        type: 'line',
                        areaStyle: {
                            normal: {}
                        },
                        data: visits,
                        markPoint: {
                            data: [{
                                name: '周最低',
                                value: visits.reduce((a, b) => Math.min(a, b), Infinity),
                                xAxis: dates.indexOf(minDate(visits)),
                                yAxis: 0
                            }]
                        },
                        markLine: {
                            data: [{
                                type: 'average',
                                name: '平均值'
                            },
                                [{
                                    symbol: 'none',
                                    x: '90%',
                                    yAxis: 'max'
                                }, {
                                    symbol: 'circle',
                                    label: {
                                        normal: {
                                            position: 'start',
                                            formatter: '最大值'
                                        }
                                    },
                                    type: 'max',
                                    name: '最高点'
                                }]
                            ]
                        }
                    }
                ]
            };

            // 显示图表
            myChart.setOption(option)
        })
        // 寻找访问量的最小日期
    }
    function minDate(values) {
    return values.reduce((minIndex, val, index) => val === Math.min(...values) ? index : minIndex, 0);
}

onMounted(() => {
  getVipUsers(),getData1(),getData2();
});

</script>

<style scoped></style>
